<template>
  <div class="chart-container" ref="chartRef"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from "vue";
import * as echarts from "echarts";
import { useScreenStore } from "@/store/modules/screen";

const screenStore = useScreenStore();

// 计算属性：从 store 中获取 orders 数据并转换为图表格式
const chartData = computed(() => {
  const ordersData = screenStore.orders;


  // 如果 store 中有 orders 数据，处理数据格式
  if (ordersData && Array.isArray(ordersData) && ordersData.length > 0) {
    // 按年份分组数据
    const data2024 = ordersData.filter(item => item.type === '2025');
    const data2025 = ordersData.filter(item => item.type === '2024');

    // 提取月份标签（去重并排序）
    const months = [...new Set(ordersData.map(item => {
      const date = new Date(item.x + '-01');
      return (date.getMonth() + 1) + '月';
    }))].sort((a, b) => {
      const monthA = parseInt(a.replace('月', ''));
      const monthB = parseInt(b.replace('月', ''));
      return monthA - monthB;
    });

    // 构建 2024 年数据
    const dataY1 = months.map(month => {
      const monthNum = parseInt(month.replace('月', ''));
      const found = data2024.find(item => {
        const date = new Date(item.x + '-01');
        return (date.getMonth() + 1) === monthNum;
      });
      return found ? found.y : 0;
    });

    // 构建 2025 年数据
    const dataY2 = months.map(month => {
      const monthNum = parseInt(month.replace('月', ''));
      const found = data2025.find(item => {
        const date = new Date(item.x + '-01');
        return (date.getMonth() + 1) === monthNum;
      });
      return found ? found.y : 0;
    });

    console.log('Processed chart data:', { dataX: months, dataY1, dataY2 });

    return {
      dataX: months,
      dataY1: dataY1,
      dataY2: dataY2,
    };
  }

  // 否则使用默认数据
  return {
    dataX: ["1月", "2月", "3月", "4月", "5月", "6月", "7月"],
    dataY1: [120, 200, 150, 80, 70, 110, 130],
    dataY2: [80, 90, 100, 130, 140, 180, 210],
  };
});

const chartRef = ref(null);
let chartInstance = null;

// 封装初始化图表的函数
const initChart = () => {
  if (chartInstance) chartInstance.dispose(); // 销毁旧实例
  chartInstance = echarts.init(chartRef.value);

  const option = {
    tooltip: {
      show: true,
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
    },
    grid: {
      top: "18%",
      left: "2%",
      right: "2%",
      bottom: "10%",
      containLabel: true,
    },
    legend: {
      show: true,
      left: "0%",
      top: "2%",
    },
    xAxis: {
      boundaryGap: true,
      data: chartData.value.dataX,
      axisLine: {
        lineStyle: {
          color: "#E6EBF1",
          fontSize: 14,
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#8C8C8C",
      },
    },
    yAxis: [
      {
        name: "",
        type: "value",
        inverse: false,
        splitLine: {
          show: true,
          lineStyle: {
            color: "#E6EBF1",
          },
        },
        axisLabel: {
          textStyle: {
            color: "#8C8C8C",
            fontSize: 14,
          },
        },
        axisTick: {
          show: false,
        },
      },
    ],
    series: [
      {
        name: "2025",
        type: "line",
        symbolSize: 7,
        smooth: true,
        data: chartData.value.dataY1,
      },
      {
        name: "2024",
        type: "line",
        symbolSize: 7,
        smooth: true,
        data: chartData.value.dataY2,
      },
    ],
  };
  chartInstance.setOption(option);
};

onMounted(() => {
  // 组件挂载时初始化图表
  if (chartRef.value) {
    initChart();
  }

  // 响应式resize
  const handleResize = () => chartInstance && chartInstance.resize();
  window.addEventListener("resize", handleResize);
  onUnmounted(() => {
    window.removeEventListener("resize", handleResize);
    chartInstance && chartInstance.dispose();
  });
});

watch(
  () => chartData.value,
  () => initChart(),
  { deep: true }
);
</script>

<style scoped>
.chart-container {
  width: 100%;
  /* 自适应父容器宽度 */
  height: 100%;
}
</style>
